<script setup>
import {ref} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {getNodeTreeApi, readRoleApi, saveRoleApi} from '@/service/auth.js'; // 假设你有一个添加角色的 API
const emit = defineEmits(['reload']);
const reload = () => {
  emit('reload');
}

const dialogVisible = ref(false);

const form = ref({
  id: '',
  title: '',
  pc: [],
});

// 设置form的验证规则
const rules = ref({
  title: [
    {required: true, message: '请输入角色名称', trigger: 'blur'}
  ]
});

// 初始化form
const initForm = () => {
  form.value = {
    id: '',
    title: '',
    pc: [],
  };
};

// 读取节点树
const nodeTree = ref([]);
const getNodeTree = async () => {
  try {
    const response = await getNodeTreeApi();
    if (response.code === 200) {
      nodeTree.value = response.data.tree;
    } else {
      ElMessage.error(response.message);
    }
  } catch (error) {
    ElMessage.error('获取节点树失败，请稍后重试');
  }
};

// 读取角色信息
const readRole = async (id) => {
  try {
    const response = await readRoleApi({id});
    if (response.code === 200) {
      form.value = response.data;
    } else {
      ElMessage.error(response.message);
    }
  } catch (error) {

    ElMessage.error('获取角色信息失败，请稍后重试');
  }
};

const openDialog = (row) => {
  if (row) {
    readRole(row.id);
  }
  dialogVisible.value = true;
  // 读取节点树
  getNodeTree();
};

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  initForm();
};

const formRef = ref(null);
const treeRef = ref(null);
const handleSave = () => {
  // 表单验证后提交
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 获取选中的节点和半选中的节点
        let checkedKeys = treeRef.value.getCheckedKeys();
        let halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
        let checkedNodes = checkedKeys.concat(halfCheckedKeys);
        form.value.pc = checkedNodes;
        const response = await saveRoleApi(form.value);
        if (response.code === 200) {
          ElMessage.success(response.msg);
          closeDialog();
          reload();
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        console.log(error);
        ElMessage.error('添加角色失败，请稍后重试');
      }
    } else {
      return false;
    }
  });
};

// 暴漏给父组件的方法
defineExpose({
  openDialog
});
</script>

<template>
  <el-drawer v-model="dialogVisible" title="配置校色" size="30%">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
      <el-form-item label="节点">
        <el-tree ref="treeRef" :data="nodeTree" :props="{ label: 'title' }" node-key="id" :default-checked-keys="form.pc" default-expand-all show-checkbox></el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-drawer>
</template>

<style scoped>
/* 添加一些样式以适应你的需求 */
</style>
